import axios from "axios";
import Qs from "qs";
// import bus from "../vue-bus";
import { Message } from "element-ui";

// import router from "../router";

import Storage from "@/assets/js/ls";
const ls = new Storage();
//
axios.defaults.withCredentials = true;
// 解决axios传参后台接收不到问题    https://blog.csdn.net/csdn_yudong/article/details/79668655
// axios.defaults.headers.common["Authorization"] = AUTH_TOKEN;
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8"; // 配置请求头
// axios.defaults.headers.get["Content-Type"] = "application/json;charset=UTF-8"; // 配置请求头
axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers.common["Authorization"] = "Bearer test1";
axios.defaults.timeout = 300000 //设置超时时间为3000ms
// 添加一个请求拦截器
// axios.interceptors.request.use(function (config) {
//   console.dir(config);
//   return config;
// }, function (error) {
//   // Do something with request error
//   return Promise.reject(error);
// });

// 添加一个响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.request.responseType === "blob") {
      console.log("导出文件");
    } else if (response.data) {
      if (parseInt(response.data.key, 10) === 1001) {
        ls.remove("mujinguserInfo");
        ls.remove("mujingtoken");
        ls.remove("mujingpermissionList");
        ls.remove("mujingpermissionNameList");
        location.reload();
        // router.push({
        //   path: "/login"
        // });
      } else if (parseInt(response.data.key, 10) !== 1000) {
        Message({
          type: "warning",
          message: response.data.message,
          customClass: 'global-message-zindex',
        });
      }
    }
    // if (response.data && response.data.key) {
    //   if (parseInt(response.data.key) === 0) {
    //     //未登录
    //     // bus.$emit("goto", "/login")
    //   }
    // }

    return response;
  },
  error => {
    // Do something with response error
    return Promise.reject(error);
  }
);

// 基地址
// const base = "/admin-api/yiHuo/manager/pc"; // 接口代理地址参见：config/index.js中的proxyTable配置
const base = "/checkorder/manager/pc" // 接口代理地址参见：config/index.js中的proxyTable配置

// //通用方法
export const POST = (url, params, contentType, type) => {
  let token = ls.get("mujingtoken");
  if (contentType) {
    return axios
      .post(`${base}${url}?token=${token}`, params, {
        "Content-Type":contentType,
        timeout: 600000,
      })
      .then(res => res.data);
  } else {
    params.token = token
    if(type){
      return axios
        .post(`${base}${url}?token=${token}`, Qs.stringify(params))
        .then(res => res.data);
    }else{
      return axios
        .post(`${base}${url}?token=${token}`, params, {
          "Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",
        })
        .then(res => res.data);
    }
  }
};

export const POSTFILE = (url, params, contentType, bol) => {
  if (!bol) {
    let token = ls.get("mujingtoken");
    return axios
      .post(`${base}${url}?token=${token}`, params, {
        "Content-Type": contentType,
        timeout: 600000,
        responseType: 'blob'
      })
      .then(res => res);
  } else {
    return axios
      .post(`${base}${url}`, Qs.stringify(params), {
        timeout: 600000,
        responseType: 'blob'
      })
      .then(res => res);
  }
};


export const POSTPROJECTFILE = (url, params) => {
  let token = ls.get("mujingtoken");
  // 1. 创建FormData对象（必须用它来处理文件上传）
  const formData = new FormData();
  // 2. 遍历参数，添加到FormData中（包括文件和普通参数）
  Object.keys(params).forEach(key => {
    formData.append(key, params[key]);
  });
  // 3. 添加token（建议放请求头，这里保持与原代码一致放参数中）
  formData.append("token", token);
  return axios
    .post(`${base}${url}`, formData, {  // 注意：URL中无需重复加token（已在formData中）
      // 2. 关键：不要手动设置Content-Type，让浏览器自动处理（会自动添加boundary）
      timeout: 600000,
      responseType: 'blob',
      headers: {
        // 移除手动设置的Content-Type，或设置为undefined
        // "Content-Type": "multipart/form-data"  // 这行必须删除！
      }
    })
    .then(res => res);
};

export const GET = (url, params) => {
  return axios
    .get(`${base}${url}`, {
      timeout: 600000,
      params
    })
    .then(res => res.data);
};

export const PUT = (url, params) => {
  return axios.put(`${base}${url}`, params).then(res => res.data);
};

export const DELETE = (url, params) => {
  return axios
    .delete(`${base}${url}`, {
      params
    })
    .then(res => res.data);
};

export const PATCH = (url, params) => {
  return axios.patch(`${base}${url}`, params).then(res => res.data);
};
